const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 30,
    page: 1,
    total_page: 0,
    wineList: [], //列表
    numbers: 0,
    selectedGoods: [], //已选商品列表 
    lastTime: 0,
  },

  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: options.userName + '的酒柜'
    });
    this.setData({
      uid: options.uid,
    })
    this.toTop();
    wx.hideShareMenu() // 隐藏分享按钮
    
    wx.setStorageSync('begSuccess', 'fail'); //缓存讨酒是否成功
  },

  toTop: function() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 10
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function(options) {
    var begSuccess = wx.getStorageSync('begSuccess');
    this.wineList();
    if (begSuccess =='success'){
      this.cleanSelected();
    }
  },

  //页面下拉刷新
  onPullDownRefresh: function() {
    var that = this;
    setTimeout(function() {
      that.resetData()
    }, 1000)
  },

  //刷新页面
  resetData: function() {
    var that = this
    that.setData({
      page: 1,
    });
    that.wineList();
  },

  //页面上拉触底
  onReachBottom: function(e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function() {
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },


  //酒柜列表
  wineList: function() {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit,
        uid: that.data.uid
      },
      url: app.globalData.base_url + 'Winecabinet/getListByUid',
      success: function(res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          if (currentPage == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.wineList.concat(resultList);
          }
          that.split_array(itemData, 3, that.data.selectedGoods);
          that.setData({
            total_page: totalPage,
            wineList: itemData,
             user_info: res.data.data.user_info
          });
        } else {
          util.showError(res.data.message);
        }
        wx.stopPullDownRefresh();
      },
      fail: function(fail) {
        wx.hideLoading()
        util.showError("网络错误，请检查网络");
      }
    })
  },

   //手动输入数量
   inputNumber: function (e) {
      var that = this;
      var goods = e.currentTarget.dataset.goodsInfo;
      var num = e.detail.value;
      num = num.replace(/^0/g, 1);
      var reg = /^\s*$/g;
      if (reg.test(num) || num == null || num == "") {
         num = '';
      } else {
         if (num > goods.num / 1) {
            util.showError("库存不足");
            num = goods.num;
         }
      }
      var selectedGoods = that.data.selectedGoods;
      var selected_len = selectedGoods.length;
      for (var j = 0; j < selected_len; j++) {
         if (goods.id == selectedGoods[j].id) {
            selectedGoods[j].selected_num = num;
            break;
         }
      }
      that.setData({
         selectedGoods: selectedGoods
      })
      var arr = that.data.wineList;
      that.split_array(arr, 3, selectedGoods)
      that.total_num(1);
   },

   //检查输入数量是否为空
   checkInputNumber: function (e) {
      var that = this;
      var goods = e.currentTarget.dataset.goodsInfo;
      if (goods.selected_num == '') {
         var selectedGoods = that.data.selectedGoods;
         var selected_len = selectedGoods.length;
         for (var j = 0; j < selected_len; j++) {
            if (goods.id == selectedGoods[j].id) {
               selectedGoods[j].selected_num = 1;
               break;
            }
         }
         that.setData({
            selectedGoods: selectedGoods
         })
         var arr = that.data.wineList;
         that.split_array(arr, 3, selectedGoods)
         that.total_num(1);
      }
   },

  //增加数量
  addNum: function(e) {
    var that = this;
    var goods = e.currentTarget.dataset.goodsInfo;
    if (goods.selected_num < goods.num) {
      var selectedGoods = that.data.selectedGoods;
      var selected_len = selectedGoods.length;
      for (var j = 0; j < selected_len; j++) {
        if (goods.id == selectedGoods[j].id) {
          selectedGoods[j].selected_num = selectedGoods[j].selected_num + 1;
          break;
        }
      }
      that.setData({
        selectedGoods: selectedGoods
      })
      var arr = that.data.wineList;
      that.split_array(arr, 3, selectedGoods)
      that.total_num(1);
    }
  },

  //减少数量
  minusNum: function(e) {
    var that = this;
    var goods = e.currentTarget.dataset.goodsInfo;
    if (goods.selected_num > 0) {
      var selectedGoods = that.data.selectedGoods;
      var selected_len = selectedGoods.length;
      for (var j = 0; j < selected_len; j++) {
        if (goods.id == selectedGoods[j].id) {
          if (goods.selected_num == 1) {
            selectedGoods.splice(j, 1);
          } else {
            selectedGoods[j].selected_num = selectedGoods[j].selected_num - 1;
          }
          break;
        }
      }
      that.setData({
        selectedGoods: selectedGoods
      })
      var arr = that.data.wineList;
      that.split_array(arr, 3, selectedGoods)
      that.total_num(2);
    }
  },

  //拆分数组
  split_array: function(arr, len, selectedGoods) {
    var a_len = arr.length;
    var box_arr = [];
    var item = [];
    var selected_len = selectedGoods.length;
    for (var i = 0; i < a_len; i++) {
      arr[i].selected_num = 0;
      for (var j = 0; j < selected_len; j++) {
        if (arr[i].id == selectedGoods[j].id) {
          arr[i].selected_num = selectedGoods[j].selected_num
        }
      }
    }

    for (var i = 0; i < a_len; i += len) {
      box_arr.push(arr.slice(i, i + len));
    }
    if (box_arr.length < 4) {
      var arr_new = [];
      for (var n = box_arr.length; n < 4; n++) {
        box_arr.push(arr_new);
      }
    }
    this.setData({
      newProductData: box_arr
    })
  },

  //商品点击事件
  intoSelect: function(e) {
    var that = this;
    var goods = e.currentTarget.dataset.goodsInfo;
    if (goods.selected_num == 0 && goods.id != null) {
      var arr = that.data.wineList;
      var selectedGoods = that.data.selectedGoods;
      goods.selected_num = 1;
      selectedGoods.push(goods);
      that.setData({
        selectedGoods: selectedGoods
      })
      
      that.split_array(arr, 3, selectedGoods)
      that.total_num(1);
    }
  },

  // 计算总数量
  total_num: function(types = 1) {
     var that=this;
     var selectedGoods = that.data.selectedGoods;
     var selected_len = selectedGoods.length;
     var total_num=0;
     for (var i = 0; i < selected_len; i++) {
        if (selectedGoods[i].selected_num>0) {
           total_num += selectedGoods[i].selected_num/1
         } 
     }
     that.setData({
       numbers: total_num
    })
  },

  //清除选中商品
  cleanSelected: function() {
    var that = this;
    var arr = that.data.wineList;
    that.split_array(arr, 3, [])
    that.setData({
      numbers: 0,
      selectedGoods: []
    })
  },

  //向TA讨酒
  begWine:function(){
    var that=this;
    setTimeout(function(){
       if (that.data.numbers > 0) {
          var list = [];
          var arr = that.data.wineList;
          var a_len = arr.length;
          var selectedGoods = that.data.selectedGoods;
          var selected_len = selectedGoods.length;
          for (var i = 0; i < a_len; i++) {
             for (var j = 0; j < selected_len; j++) {
                if (arr[i].id == selectedGoods[j].id) {
                   list.push(selectedGoods[j]);
                   break;
                }
             }
          }
          // console.log(list)
          wx.redirectTo({
             url: '/play/pages/begWineList/begWineList?uid=' + that.data.uid + '&goodsList=' + JSON.stringify(list),
          })
       } else {
          util.showError('请选择商品!');
       }
    },500)
    
  }
})